<template>
  <el-card shadow="hover" class="mt-20">
    <el-form
      label-width="100px"
      ref="skuFormRef"
      :model="skuFormData"
      :rules="skuFormRules"
    >
      <el-form-item label="SPU名称">
        <span>{{ spuStore.spuName }}</span>
      </el-form-item>

      <el-form-item label="SKU名称" prop="skuName">
        <el-input
          placeholder="请输入SKU名称"
          v-model="skuFormData.skuName"
        ></el-input>
      </el-form-item>

      <el-form-item label="价格(元)" prop="price">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.price"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="重量(KG)" prop="weight">
        <el-input-number
          :min="0"
          controls-position="right"
          class="sku-input-number"
          v-model="skuFormData.weight"
        ></el-input-number>
      </el-form-item>

      <el-form-item label="规格描述" prop="skuDesc">
        <el-input
          placeholder="请输入规格描述"
          type="textarea"
          :rows="3"
          v-model="skuFormData.skuDesc"
        ></el-input>
      </el-form-item>

      <el-form-item label="平台属性" prop="skuAttrValueList">
        <el-row class="sku-row">
          <el-col
            v-bind="responsiveLayout"
            class="sku-col"
            v-for="(attrItem, index) in attrList"
            :key="attrItem.id"
          >
            <span class="sku-select-title">{{ attrItem.attrName }}</span>
            <!-- 如何收集多个select数据，收集到一个数组中 -->
            <el-select
              class="sku-select"
              v-model="skuFormData.skuAttrValueList[index]"
            >
              <el-option
                v-for="attrValueItem in attrItem.attrValueList"
                :key="attrValueItem.id"
                :label="attrValueItem.valueName"
                :value="`${attrItem.id}:${attrItem.attrName}:${attrValueItem.id}:${attrValueItem.valueName}`"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="销售属性" prop="skuSaleAttrValueList">
        <el-row class="sku-row">
          <el-col
            v-bind="responsiveLayout"
            class="sku-col"
            v-for="(saleAttrItem, index) in spuSaleAttrList"
            :key="saleAttrItem.id"
          >
            <span class="sku-select-title">
              {{ saleAttrItem.saleAttrName }}
            </span>
            <el-select
              class="sku-select"
              v-model="skuFormData.skuSaleAttrValueList[index]"
            >
              <el-option
                v-for="saleAttrValueItem in saleAttrItem.spuSaleAttrValueList"
                :key="saleAttrValueItem.id"
                :label="saleAttrValueItem.saleAttrValueName"
                :value="`${saleAttrItem.id}:${saleAttrItem.saleAttrName}:${saleAttrValueItem.id}:${saleAttrValueItem.saleAttrValueName}`"
              ></el-option>
            </el-select>
          </el-col>
        </el-row>
      </el-form-item>

      <el-form-item label="图片列表" prop="skuImageList">
        <el-table
          :data="spuImageList"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="图片">
            <template v-slot="{ row }">
              <img :src="row.imgUrl" :alt="row.imgName" class="sku-img" />
            </template>
          </el-table-column>
          <el-table-column label="名称" prop="imgName"> </el-table-column>
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <!-- <el-button
                type="primary"
                size="small"
                v-if="row.isDefault === '0'"
              >
                设置默认图片
              </el-button>
              <el-tag type="success" v-else>默认图片</el-tag> -->
              <el-tag type="success" v-if="row.isDefault === '1'">
                默认图片
              </el-tag>
              <el-button
                type="primary"
                size="small"
                v-else
                @click="setSkuDefaultImg(row)"
              >
                设置默认图片
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="addOrUpdateSku">保存</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from "vue";
import { getAttrListApi } from "@/api/product/attr";
import { getSpuImageListApi, getSpuSaleAttrListApi } from "@/api/product/spu";
import type { AttrList } from "@/api/product/models/attrModels";
import type {
  SpuImageList,
  SpuImageItem,
  SpuSaleAttrList,
} from "@/api/product/models/spuModels";
import type { SkuFormData } from "@/api/product/models/skuModels";
import { useCategoryStore } from "@/stores/category";
import { useSpuStore } from "@/stores/spu";
import { addSkuApi } from "@/api/product/sku";

defineOptions({
  name: "AddSku",
});

// 5. 设置默认图片
const setSkuDefaultImg = (row: SpuImageItem) => {
  spuImageList.value.forEach((img) => (img.isDefault = "0"));
  row.isDefault = "1";
  skuFormData.skuDefaultImg = row.imgUrl;
  // 重新校验图片表单项
  skuFormRef.value.validateField(["skuImageList"]);
};

// 4. 收集数据和表单校验
const skuFormRef = ref();

const skuFormData = reactive<SkuFormData>({
  skuName: "",
  price: 0,
  weight: 0,
  skuDesc: "",
  skuAttrValueList: [
    // {
    //   "attrId": 0,
    //   "attrName": "string",
    //   "valueId": 0,
    //   "valueName": "string"
    // }
  ],
  skuSaleAttrValueList: [
    // {
    //   saleAttrId: 0,
    //   saleAttrName: "string",
    //   saleAttrValueId: 0,
    //   saleAttrValueName: "string",
    // },
  ],
  skuImageList: [
    // {
    //   imgName: "string",
    //   imgUrl: "string",
    //   isDefault: "string", // 是否是默认图片 '0' '1'
    // },
  ],
  skuDefaultImg: "", // 默认图片url
});

const skuImageListValidator = (
  _rule: any,
  value: SpuImageList,
  callback: any
) => {
  // 1. 至少选择一张图片
  if (!value.length) {
    callback(new Error("请至少选择一张图片！"));
    return;
  }

  // if (spuImageList.value.some((img) => img.isDefault === "1")) {
  //   // 有设置默认图片
  //   // 判断设置默认图片是否被选中
  //   if (!value.some((img) => img.isDefault === "1")) {
  //     callback(new Error("默认图片必须选中！"));
  //     return;
  //   }
  // } else {
  //   // 没有设置默认图片
  //   callback(new Error("请设置默认图片！"));
  //   return;
  // }

  if (!spuImageList.value.some((img) => img.isDefault === "1")) {
    callback(new Error("请设置默认图片！"));
    return;
  }

  if (!value.some((img) => img.isDefault === "1")) {
    callback(new Error("默认图片必须选中！"));
    return;
  }

  callback();
};

const skuFormRules = reactive({
  skuName: [{ required: true, message: "请输入SKU名称", trigger: "blur" }],
  price: [{ required: true, message: "请输入SKU价格", trigger: "blur" }],
  weight: [{ required: true, message: "请输入SKU重量", trigger: "blur" }],
  skuDesc: [{ required: true, message: "请输入SKU规格描述", trigger: "blur" }],
  skuAttrValueList: [
    { required: true, message: "请选择SKU平台属性", trigger: "change" },
  ],
  skuSaleAttrValueList: [
    { required: true, message: "请选择SKU销售属性", trigger: "change" },
  ],
  skuImageList: [
    { required: true, validator: skuImageListValidator, trigger: "change" },
  ],
});

const addOrUpdateSku = async () => {
  await skuFormRef.value.validate();

  await addSkuApi({
    category3Id: categoryStore.category3Id,
    ...skuFormData,
    skuAttrValueList: skuFormData.skuAttrValueList
      .filter(Boolean)
      .map((attr) => {
        const [attrId, attrName, valueId, valueName] = attr.split(":");
        return {
          attrId: +attrId,
          attrName,
          valueId: +valueId,
          valueName,
        };
      }),
    skuSaleAttrValueList: skuFormData.skuSaleAttrValueList
      .filter(Boolean)
      .map((saleAttr) => {
        const [saleAttrId, saleAttrName, saleAttrValueId, saleAttrValueName] =
          saleAttr.split(":");
        return {
          saleAttrId: +saleAttrId,
          saleAttrName,
          saleAttrValueId: +saleAttrValueId,
          saleAttrValueName,
        };
      }),
    spuId: spuStore.id,
  });

  ElMessage.success("添加SKU成功");

  cancel();
};

const handleSelectionChange = (val: SpuImageList) => {
  // val 就是复选框选中的值
  skuFormData.skuImageList = val;
};

// 3. 获取 平台属性、销售属性、图片列表数据展示
const attrList = ref<AttrList>([]);
const spuSaleAttrList = ref<SpuSaleAttrList>([]);
const spuImageList = ref<SpuImageList>([]);

const categoryStore = useCategoryStore();

onMounted(async () => {
  attrList.value = await getAttrListApi({
    category1Id: categoryStore.category1Id as number,
    category2Id: categoryStore.category2Id as number,
    category3Id: categoryStore.category3Id as number,
  });
});

const spuStore = useSpuStore();

onMounted(async () => {
  spuSaleAttrList.value = await getSpuSaleAttrListApi(spuStore.id as number);
});

onMounted(async () => {
  spuImageList.value = await getSpuImageListApi(spuStore.id as number);
});

// 2. select 响应式布局
const responsiveLayout = {
  xs: 24,
  sm: 12,
  md: 8,
  lg: 6,
  xl: 4,
};

// 1. 取消
const emit = defineEmits(["setIsShow"]);

const cancel = () => {
  emit("setIsShow", 1);
};
</script>

<style scoped lang="scss">
.sku-input-number {
  width: 100%;
}

:deep(.el-input__inner) {
  text-align: left;
}

.sku-col {
  display: flex;
  margin-bottom: 10px;
}
.sku-select-title {
  width: 80px;
  text-align: right;
  margin-right: 10px;
  // 单行文字溢出隐藏
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}

.sku-select {
  flex: 1;
}

.sku-row {
  width: 100%;
}

.sku-img {
  width: 100px;
  height: 100px;
}
</style>
